/**
 * 
 */
package com.wistech.search.solr.extend.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Maps;
import com.wistech.commons.dao.hibernate.HibernateDao;
import com.wistech.search.solr.extend.model.Company;

/**
 * @author Liuye
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Repository
public class CompanyDao extends HibernateDao<Company, String> {
	private static final String QUERY_USER_ID_BY_ONLINE_SQL = "SELECT id FROM company WHERE online=?";
	private static final String QUERY_SCORE = "SELECT score FROM company WHERE id=?";
	private static final String QUERY_ALL_SCORE = "SELECT id,score FROM company";

	public List<String> findCompanyIdsByOnline(final boolean online) {
		return (List<String>) getHibernateTemplate().executeWithNativeSession(
				new HibernateCallback() {
					public Object doInHibernate(final Session session)
							throws HibernateException {
						final Query q = session.createSQLQuery(
								QUERY_USER_ID_BY_ONLINE_SQL).addScalar("id",
								StandardBasicTypes.STRING);
						q.setParameter(0, online);
						return q.list();
					}
				});
	}

	public Float getScore(final String id) {
		return (Float) getHibernateTemplate().executeWithNativeSession(
				new HibernateCallback() {
					public Object doInHibernate(final Session session)
							throws HibernateException {
						final Query q = session.createSQLQuery(QUERY_SCORE)
								.addScalar("score", StandardBasicTypes.FLOAT);
						q.setParameter(0, id);
						return q.uniqueResult();
					}
				});
	}

	public Map<String, Float> getAllScores() {
		List<Map<String, Object>> scoreList = (List<Map<String, Object>>) getHibernateTemplate()
				.executeWithNativeSession(new HibernateCallback() {
					public Object doInHibernate(final Session session)
							throws HibernateException {
						final Query q = session.createSQLQuery(QUERY_ALL_SCORE)
								.addScalar("id", StandardBasicTypes.STRING)
								.addScalar("score", StandardBasicTypes.FLOAT);
						q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
						return q.list();
					}
				});
		Map<String, Float> scores = Maps.newHashMap();
		for (Map<String, Object> score : scoreList) {
			scores.put((String) score.get("id"), (Float) score.get("score"));
		}
		return scores;
	}
}
